package com.asset.dispoal.menu.service.commom;

import com.asset.dispoal.menu.domain.db.entity.GbMenuDo;
import com.asset.dispoal.menu.domain.db.mapper.GbMenuMapper;
import com.asset.dispoal.menu.dto.response.GbMenuResponse;
import com.asset.dispoal.menu.service.converter.MenuConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2022/3/14$
 */
@Component
public class CompanyMenuCommand implements BaseCommand<Map<String, String>, Result<List<GbMenuResponse>>> {


    @Autowired
    GbMenuMapper gbMenuMapper;

    @Override
    public Result<List<GbMenuResponse>> execute(Map<String, String> map) {
        String companyType = map.get("companyType");
        String companyId = map.get("companyId");
        List<GbMenuDo> gbMenuDos;
        if (StringUtil.isNotBlank(companyType)) {
            gbMenuDos = gbMenuMapper.queryAll();
        } else {
            gbMenuDos = gbMenuMapper.queryDefaultMenuByCompanyId(companyId);

        }
        final List<String> list = gbMenuMapper.queryMenuByCompany(companyType, companyId);

        for (String id : list) {
            for (GbMenuDo gbMenuDo : gbMenuDos) {
                if (id.contains(gbMenuDo.getId())) {
                    gbMenuDo.setCompanySate("1");
                }
            }
        }
        List<GbMenuResponse> gbMenuResponses = MenuConverter.INSTANCE.doToRes(gbMenuDos);
        for (GbMenuResponse parent : gbMenuResponses) {
            for (GbMenuResponse menu : gbMenuResponses) {
                if (parent.getId().equals(menu.getParentId())) {
                    parent.getGbMenuResponse().add(menu);
                    parent.getGbMenuResponse().sort(Comparator.comparingInt(GbMenuResponse::getSorted));
                }
            }
        }
        final List<GbMenuResponse> gbMenuResponseStream = gbMenuResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());
        return Result.ok(gbMenuResponseStream);
    }
}
